import { http } from "@/utils/http";
import type { ApiResponse } from "./user";

/** 敏感词类型枚举 */
export enum SensitiveWordType {
  PROFANITY = "profanity",
  POLITICS = "politics",
  ADVERTISEMENT = "advertisement",
  VIOLENCE = "violence",
  ILLEGAL = "illegal",
  SPAM = "spam"
}

/** 过滤模式枚举 */
export enum FilterMode {
  REPLACE = "REPLACE",
  BLOCK = "BLOCK"
}

/** 严重程度枚举 */
export enum SeverityLevel {
  LIGHT = 1, // 轻微
  NORMAL = 2, // 一般
  MEDIUM = 3, // 中等
  SERIOUS = 4, // 严重
  CRITICAL = 5 // 极严重
}

/** 敏感词信息 */
export interface SensitiveWordInfo {
  /** 敏感词ID */
  id: number;
  /** 敏感词内容 */
  word: string;
  /** 敏感词类型 */
  type: SensitiveWordType;
  /** 类型描述 */
  typeDescription: string;
  /** 严重程度 */
  severity: SeverityLevel;
  /** 严重程度描述 */
  severityDescription: string;
  /** 过滤模式 */
  filterMode: FilterMode;
  /** 过滤模式描述 */
  filterModeDescription: string;
  /** 替换文本 */
  replacement?: string;
  /** 状态 */
  status: number;
  /** 状态描述 */
  statusDescription: string;
  /** 描述信息 */
  description?: string;
  /** 标签JSON字符串 */
  tags?: string;
  /** 标签列表 */
  tagList?: string[];
  /** 匹配次数 */
  matchCount: number;
  /** 最后匹配时间 */
  lastMatchTime?: string;
  /** 创建人ID */
  createBy: number;
  /** 创建人姓名 */
  createByName: string;
  /** 创建时间 */
  createTime: string;
  /** 更新人ID */
  updateBy?: number;
  /** 更新人姓名 */
  updateByName?: string;
  /** 更新时间 */
  updateTime?: string;
}

/** 敏感词查询参数 */
export interface SensitiveWordQuery {
  /** 当前页码 */
  current?: number;
  /** 每页大小 */
  size?: number;
  /** 敏感词内容（模糊查询） */
  word?: string;
  /** 敏感词类型 */
  type?: SensitiveWordType;
  /** 严重程度 */
  severity?: SeverityLevel;
  /** 过滤模式 */
  filterMode?: FilterMode;
  /** 状态 */
  status?: number;
  /** 创建人ID */
  createBy?: number;
  /** 开始时间 */
  startTime?: string;
  /** 结束时间 */
  endTime?: string;
  /** 标签（模糊查询） */
  tags?: string;
  /** 排序字段 */
  sortField?: string;
  /** 排序方向 */
  sortOrder?: "asc" | "desc";
}

/** 敏感词创建参数 */
export interface CreateSensitiveWordParams {
  /** 敏感词内容 */
  word: string;
  /** 敏感词类型 */
  type: SensitiveWordType;
  /** 严重程度 */
  severity: SeverityLevel;
  /** 过滤模式 */
  filterMode: FilterMode;
  /** 替换文本 */
  replacement?: string;
  /** 描述信息 */
  description?: string;
  /** 分类标签数组 */
  tags?: string[];
  /** 状态 */
  status?: number;
}

/** 敏感词更新参数 */
export interface UpdateSensitiveWordParams {
  /** 敏感词ID */
  id: number;
  /** 敏感词内容 */
  word?: string;
  /** 敏感词类型 */
  type?: SensitiveWordType;
  /** 严重程度 */
  severity?: SeverityLevel;
  /** 过滤模式 */
  filterMode?: FilterMode;
  /** 替换文本 */
  replacement?: string;
  /** 描述信息 */
  description?: string;
  /** 分类标签数组 */
  tags?: string[];
  /** 状态 */
  status?: number;
}

/** 批量操作参数 */
export interface BatchOperationParams {
  /** 敏感词ID列表 */
  ids: number[];
  /** 操作类型 */
  operation: "enable" | "disable" | "delete";
  /** 操作原因 */
  reason?: string;
}

/** 批量创建敏感词参数 */
export interface BatchCreateSensitiveWordsParams {
  /** 敏感词列表 */
  words: string[];
  /** 敏感词类型 */
  type: SensitiveWordType;
  /** 严重程度 */
  severity: SeverityLevel;
  /** 过滤模式 */
  filterMode: FilterMode;
  /** 替换文本 */
  replacement?: string;
  /** 描述信息 */
  description?: string;
  /** 分类标签数组 */
  tags?: string[];
  /** 状态 */
  status?: number;
  /** 是否覆盖已存在的敏感词 */
  overwrite?: boolean;
}

/** 批量创建结果 */
export interface BatchCreateResult {
  /** 成功数量 */
  successCount: number;
  /** 失败数量 */
  failedCount: number;
  /** 已存在数量 */
  existingCount: number;
  /** 成功的敏感词 */
  successWords: string[];
  /** 失败的敏感词 */
  failedWords: string[];
  /** 已存在的敏感词 */
  existingWords: string[];
}

/** 批量状态更新参数 */
export interface BatchStatusUpdateParams {
  /** 敏感词ID列表 */
  ids: number[];
  /** 状态 */
  status: number;
}

/** 热门敏感词信息 */
export interface PopularSensitiveWord {
  /** 敏感词ID */
  id: number;
  /** 敏感词内容 */
  word: string;
  /** 敏感词类型 */
  type: SensitiveWordType;
  /** 匹配次数 */
  matchCount: number;
  /** 最后匹配时间 */
  lastMatchTime: string;
}

/** 敏感词过滤测试参数 */
export interface TestFilterParams {
  /** 要测试的内容 */
  content: string;
}

/** 敏感词过滤测试结果 */
export interface TestFilterResult {
  /** 原始内容 */
  originalContent: string;
  /** 过滤后内容 */
  filteredContent: string;
  /** 是否包含敏感词 */
  hasSensitiveWords: boolean;
  /** 检测到的敏感词 */
  sensitiveWords: Array<{
    word: string;
    type: SensitiveWordType;
    severity: SeverityLevel;
    filterMode: FilterMode;
    replacement?: string;
  }>;
  /** 是否被拦截 */
  isBlocked: boolean;
}

/** 分页响应结果 */
export interface PageResult<T> {
  /** 数据列表 */
  records: T[];
  /** 总记录数 */
  total: number;
  /** 每页大小 */
  size: number;
  /** 当前页码 */
  current: number;
  /** 总页数 */
  pages: number;
}

/** 敏感词列表响应结果 */
export type SensitiveWordListResult = ApiResponse<
  PageResult<SensitiveWordInfo>
>;

/** 敏感词详情响应结果 */
export type SensitiveWordDetailResult = ApiResponse<SensitiveWordInfo>;

/** 创建敏感词响应结果 */
export type CreateSensitiveWordResult = ApiResponse<number>;

// ==================== API 接口函数 ====================

/** 分页查询敏感词列表 */
export const getSensitiveWordListApi = (params: SensitiveWordQuery) => {
  console.log("API调用: getSensitiveWordListApi", params);
  return http.request<SensitiveWordListResult>(
    "get",
    "/admin/sensitive-word/page",
    {
      params
    }
  );
};

/** 获取敏感词详情 */
export const getSensitiveWordDetailApi = (id: number) => {
  console.log("API调用: getSensitiveWordDetailApi", id);
  return http.request<SensitiveWordDetailResult>(
    "get",
    `/admin/sensitive-word/${id}`
  );
};

/** 创建敏感词 */
export const createSensitiveWordApi = (params: CreateSensitiveWordParams) => {
  console.log("API调用: createSensitiveWordApi", params);
  return http.request<CreateSensitiveWordResult>(
    "post",
    "/admin/sensitive-word",
    {
      data: params
    }
  );
};

/** 更新敏感词 */
export const updateSensitiveWordApi = (params: UpdateSensitiveWordParams) => {
  console.log("API调用: updateSensitiveWordApi", params);
  return http.request<ApiResponse>(
    "put",
    `/admin/sensitive-word/${params.id}`,
    {
      data: params
    }
  );
};

/** 删除敏感词 */
export const deleteSensitiveWordApi = (id: number) => {
  console.log("API调用: deleteSensitiveWordApi", id);
  return http.request<ApiResponse>("delete", `/admin/sensitive-word/${id}`);
};

/** 批量操作敏感词 */
export const batchOperateSensitiveWordsApi = (params: BatchOperationParams) => {
  console.log("API调用: batchOperateSensitiveWordsApi", params);
  return http.request<ApiResponse>("post", "/admin/sensitive-word/batch", {
    data: params
  });
};

/** 启用敏感词 */
export const enableSensitiveWordApi = (id: number) => {
  console.log("API调用: enableSensitiveWordApi", id);
  return http.request<ApiResponse>(
    "post",
    `/admin/sensitive-word/${id}/enable`
  );
};

/** 禁用敏感词 */
export const disableSensitiveWordApi = (id: number) => {
  console.log("API调用: disableSensitiveWordApi", id);
  return http.request<ApiResponse>(
    "post",
    `/admin/sensitive-word/${id}/disable`
  );
};

/** 更新敏感词状态 */
export const updateSensitiveWordStatusApi = (id: number, status: number) => {
  console.log("API调用: updateSensitiveWordStatusApi", id, status);
  return http.request<ApiResponse>(
    "put",
    `/admin/sensitive-word/${id}/status`,
    { params: { status } }
  );
};

/** 批量创建敏感词 */
export const batchCreateSensitiveWordsApi = (
  params: BatchCreateSensitiveWordsParams
) => {
  console.log("API调用: batchCreateSensitiveWordsApi", params);
  return http.request<ApiResponse<BatchCreateResult>>(
    "post",
    "/admin/sensitive-word/batch",
    { data: params }
  );
};

/** 批量更新状态 */
export const batchUpdateStatusApi = (params: BatchStatusUpdateParams) => {
  console.log("API调用: batchUpdateStatusApi", params);
  return http.request<ApiResponse>(
    "put",
    "/admin/sensitive-word/batch/status",
    { params }
  );
};

/** 批量删除敏感词 */
export const batchDeleteSensitiveWordsApi = (ids: number[]) => {
  console.log("API调用: batchDeleteSensitiveWordsApi", ids);
  return http.request<ApiResponse>("delete", "/admin/sensitive-word/batch", {
    params: { ids }
  });
};

/** 敏感词统计信息 */
export interface SensitiveWordStatistics {
  /** 总敏感词数 */
  totalWords: number;
  /** 启用的敏感词数 */
  enabledWords: number;
  /** 禁用的敏感词数 */
  disabledWords: number;
  /** 替换模式敏感词数 */
  replaceWords: number;
  /** 拦截模式敏感词数 */
  blockWords: number;
  /** 总匹配次数 */
  totalMatches: number;
  /** 类型数量 */
  typeCount: number;
  /** 今日新增敏感词数 */
  todayWords: number;
  /** 昨日新增敏感词数 */
  yesterdayWords: number;
}

/** 敏感词统计响应结果 */
export type SensitiveWordStatisticsResult =
  ApiResponse<SensitiveWordStatistics>;

/** 获取敏感词统计信息 */
export const getSensitiveWordStatisticsApi = () => {
  console.log("API调用: getSensitiveWordStatisticsApi");
  return http.request<SensitiveWordStatisticsResult>(
    "get",
    "/admin/sensitive-word/statistics"
  );
};

/** 获取类型分布统计 */
export const getTypeDistributionApi = () => {
  console.log("API调用: getTypeDistributionApi");
  return http.request<ApiResponse<Record<string, number>>>(
    "get",
    "/admin/sensitive-word/statistics/type-distribution"
  );
};

/** 获取严重程度分布统计 */
export const getSeverityDistributionApi = () => {
  console.log("API调用: getSeverityDistributionApi");
  return http.request<ApiResponse<Record<string, number>>>(
    "get",
    "/admin/sensitive-word/statistics/severity-distribution"
  );
};

/** 获取过滤模式分布统计 */
export const getFilterModeDistributionApi = () => {
  console.log("API调用: getFilterModeDistributionApi");
  return http.request<ApiResponse<Record<string, number>>>(
    "get",
    "/admin/sensitive-word/statistics/filter-mode-distribution"
  );
};

/** 获取热门敏感词 */
export const getPopularSensitiveWordsApi = (
  limit: number = 10,
  days: number = 30
) => {
  console.log("API调用: getPopularSensitiveWordsApi", { limit, days });
  return http.request<ApiResponse<PopularSensitiveWord[]>>(
    "get",
    "/admin/sensitive-word/popular",
    { params: { limit, days } }
  );
};

/** 敏感词检测参数 */
export interface SensitiveWordCheckParams {
  /** 待检测文本 */
  content: string;
  /** 检测模式 */
  mode?: "check" | "replace";
}

/** 敏感词检测结果 */
export interface SensitiveWordCheckResult {
  /** 是否包含敏感词 */
  hasSensitiveWords: boolean;
  /** 检测到的敏感词列表 */
  sensitiveWords: Array<{
    /** 敏感词内容 */
    word: string;
    /** 敏感词类型 */
    type: SensitiveWordType;
    /** 严重程度 */
    severity: SeverityLevel;
    /** 在文本中的位置 */
    positions: Array<{
      start: number;
      end: number;
    }>;
  }>;
  /** 处理后的文本（替换模式下） */
  processedContent?: string;
  /** 风险等级 */
  riskLevel: "low" | "medium" | "high" | "critical";
  /** 建议操作 */
  suggestedAction: "allow" | "review" | "block";
}

/** 敏感词检测响应结果 */
export type SensitiveWordCheckResultType =
  ApiResponse<SensitiveWordCheckResult>;

/** 检测敏感词 */
export const checkSensitiveWordsApi = (params: SensitiveWordCheckParams) => {
  console.log("API调用: checkSensitiveWordsApi", params);
  return http.request<SensitiveWordCheckResultType>(
    "post",
    "/admin/sensitive-word/check",
    {
      data: params
    }
  );
};

/** 导入敏感词参数 */
export interface ImportSensitiveWordsParams {
  /** 文件 */
  file: File;
  /** 敏感词类型 */
  type: SensitiveWordType;
  /** 严重程度 */
  severity: SeverityLevel;
  /** 过滤模式 */
  filterMode: FilterMode;
  /** 是否覆盖已存在的敏感词 */
  overwrite?: boolean;
}

/** 导入结果 */
export interface ImportResult {
  /** 成功导入数量 */
  successCount: number;
  /** 失败数量 */
  failedCount: number;
  /** 已存在数量 */
  existingCount: number;
  /** 总数量 */
  totalCount: number;
}

/** 导入敏感词响应结果 */
export type ImportSensitiveWordsResult = ApiResponse<ImportResult>;

/** 导入敏感词 */
export const importSensitiveWordsApi = (params: ImportSensitiveWordsParams) => {
  console.log("API调用: importSensitiveWordsApi", params);

  const formData = new FormData();
  formData.append("file", params.file);
  formData.append("type", params.type);
  formData.append("severity", params.severity.toString());
  formData.append("filterMode", params.filterMode);
  if (params.overwrite !== undefined) {
    formData.append("overwrite", params.overwrite.toString());
  }

  return http.request<ImportSensitiveWordsResult>(
    "post",
    "/admin/sensitive-word/import",
    {
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data"
      }
    }
  );
};

/** 导出敏感词 */
export const exportSensitiveWordsApi = (params: SensitiveWordQuery) => {
  console.log("API调用: exportSensitiveWordsApi", params);
  return http.request<Blob>("get", "/admin/sensitive-word/export", {
    params,
    responseType: "blob"
  });
};

/** 刷新敏感词缓存 */
export const refreshCacheApi = () => {
  console.log("API调用: refreshCacheApi");
  return http.request<ApiResponse>(
    "post",
    "/admin/sensitive-word/refresh-cache"
  );
};

/** 清理过期统计 */
export const cleanExpiredStatsApi = (days: number = 30) => {
  console.log("API调用: cleanExpiredStatsApi", days);
  return http.request<ApiResponse<number>>(
    "post",
    "/admin/sensitive-word/clean-expired-stats",
    { params: { days } }
  );
};

/** 测试敏感词过滤 */
export const testFilterApi = (params: TestFilterParams) => {
  console.log("API调用: testFilterApi", params);
  return http.request<ApiResponse<TestFilterResult>>(
    "post",
    "/admin/sensitive-word/test-filter",
    { params }
  );
};

// ==================== 工具函数 ====================

/** 敏感词管理工具类 */
export class SensitiveWordManagementUtils {
  /** 获取敏感词类型描述 */
  static getTypeDescription(type: SensitiveWordType): string {
    const typeMap = {
      [SensitiveWordType.PROFANITY]: "脏话",
      [SensitiveWordType.POLITICS]: "政治敏感",
      [SensitiveWordType.ADVERTISEMENT]: "广告",
      [SensitiveWordType.VIOLENCE]: "暴力内容",
      [SensitiveWordType.ILLEGAL]: "违法内容",
      [SensitiveWordType.SPAM]: "垃圾信息"
    };
    return typeMap[type] || "未知";
  }

  /** 获取严重程度描述 */
  static getSeverityDescription(severity: SeverityLevel): string {
    const severityMap = {
      [SeverityLevel.LIGHT]: "轻微",
      [SeverityLevel.NORMAL]: "一般",
      [SeverityLevel.MEDIUM]: "中等",
      [SeverityLevel.SERIOUS]: "严重",
      [SeverityLevel.CRITICAL]: "极严重"
    };
    return severityMap[severity] || "未知";
  }

  /** 获取过滤模式描述 */
  static getFilterModeDescription(mode: FilterMode): string {
    const modeMap = {
      [FilterMode.REPLACE]: "替换模式",
      [FilterMode.BLOCK]: "拦截模式"
    };
    return modeMap[mode] || "未知";
  }

  /** 获取状态描述 */
  static getStatusDescription(status: number): string {
    return status === 1 ? "启用" : "禁用";
  }

  /** 获取严重程度颜色 */
  static getSeverityColor(severity: SeverityLevel): string {
    const colorMap = {
      [SeverityLevel.LIGHT]: "#67C23A", // 绿色 - 轻微
      [SeverityLevel.NORMAL]: "#409EFF", // 蓝色 - 一般
      [SeverityLevel.MEDIUM]: "#E6A23C", // 橙色 - 中等
      [SeverityLevel.SERIOUS]: "#F56C6C", // 红色 - 严重
      [SeverityLevel.CRITICAL]: "#722ED1" // 紫色 - 极严重
    };
    return colorMap[severity] || "#909399";
  }

  /** 获取类型颜色 */
  static getTypeColor(type: SensitiveWordType): string {
    const colorMap = {
      [SensitiveWordType.PROFANITY]: "#F56C6C", // 红色 - 脏话
      [SensitiveWordType.POLITICS]: "#722ED1", // 紫色 - 政治敏感
      [SensitiveWordType.ADVERTISEMENT]: "#52C41A", // 绿色 - 广告
      [SensitiveWordType.VIOLENCE]: "#FF7A45", // 橙红色 - 暴力内容
      [SensitiveWordType.ILLEGAL]: "#1890FF", // 蓝色 - 违法内容
      [SensitiveWordType.SPAM]: "#FAAD14" // 黄色 - 垃圾信息
    };
    return colorMap[type] || "#909399";
  }

  /** 解析标签字符串 */
  static parseTagList(tags?: string): string[] {
    if (!tags) return [];
    try {
      return JSON.parse(tags);
    } catch {
      return [];
    }
  }

  /** 格式化标签为字符串 */
  static formatTagList(tagList?: string[]): string {
    if (!tagList || tagList.length === 0) return "";
    return JSON.stringify(tagList);
  }
}
